package com.example.springmvcwork.controller;


import io.micrometer.common.util.StringUtils;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Paths;
import java.util.UUID;

@Controller
@RequestMapping(value = "/upload")
public class FileUploadController {
    @PostMapping
    public String handleFormUpload(@RequestParam("file") MultipartFile file,
                                   Model model) throws IOException {
        if (!file.isEmpty()) {
            String originalFilename = file.getOriginalFilename();
            String targetFilename = UUID.randomUUID() +
                    originalFilename.substring(originalFilename.lastIndexOf("."));

             file.transferTo(Paths.get("./upload/",targetFilename));
           String message = String.format("上传成功：%s；文件大小：%d字节",
                    file.getOriginalFilename(),
                    file.getSize());

           model.addAttribute("message",message);
           model.addAttribute("targetFilename", targetFilename);

        }
        return "upload";
    }


    @RequestMapping(value = "/addFile")
    public String setUpUploadForm () {
        return "upload";
    }

    @GetMapping(value = "/enter")
    public String enter(){
        return "Enter";
    }

//    登录页面进行验证
    @PostMapping(value = "/interBook")
    public String interBook(@RequestParam("username")String username, @RequestParam("password")String password,
                       Model model, HttpSession session){
        if(!StringUtils.isEmpty(username) && "1234".equals(password)){
            session.setAttribute("username",username);
            return "redirect:/upload/book";
        }
        else{
            model.addAttribute("message","用户名或密码错误");
            return "Enter";
        }

    }
   @GetMapping(value = "/out")
    public String out(HttpSession session){
        session.invalidate();
        return "demo";
    }
    @GetMapping(value = "/book")
    public String book(){
        return "图书列表页";
    }

    @GetMapping(value = "/InterceptorBook")
    public String InterceptorBook(){
        return "图书列表页";
    }

    @GetMapping(value = "/InterceptorNewBook")
    public String InterceptorNewBook(){
        return "新图书登记";
    }
    @GetMapping(value = "/newBook")
    public String newBook(){
        return "新图书登记";
    }

//  接受新增图书页post提交的数据
  @PostMapping(value = "/addNewBook")
    @ResponseBody
    public String addNewBook(@RequestParam("bookName")String bookName,@RequestParam("writer")String writer
    ,@RequestParam("press")String press,@RequestParam("inputTime")String inputTime,@RequestParam("number")String number)
    {
        return "成功接受新图书登记页面发送的数据";
    }

}
